<template>
  <div class="guide-management">
    <div class="page-header">
      <h2>讲解员管理</h2>
      <el-button type="primary" @click="handleAdd">添加讲解员</el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="讲解员姓名">
          <el-input v-model="searchForm.name" placeholder="请输入讲解员姓名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="guideList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="讲解员姓名" min-width="120"></el-table-column>
        <el-table-column prop="phone" label="手机号" min-width="120"></el-table-column>
        <el-table-column prop="introduction" label="介绍" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160"></el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleChangeStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="guideFormRef"
        :model="guideForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="讲解员姓名" prop="name">
          <el-input v-model="guideForm.name" placeholder="请输入讲解员姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="guideForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="guideForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="介绍" prop="introduction">
          <el-input 
            v-model="guideForm.introduction" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入讲解员介绍"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getGuidePage, getGuideById, addGuide, updateGuide, deleteGuide } from '@/api/guide'

// 数据加载状态
const loading = ref(false)

// 列表数据
const guideList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
  status: ''
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = computed(() => guideForm.id ? '编辑讲解员' : '添加讲解员')
const guideFormRef = ref(null)
const guideForm = reactive({
  id: null,
  name: '',
  phone: '',
  introduction: '',
  status: 1
})

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入讲解员姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  introduction: [
    { max: 500, message: '介绍不能超过500个字符', trigger: 'blur' }
  ]
})

// 初始化
onMounted(() => {
  fetchGuideList()
})

// 获取讲解员列表
const fetchGuideList = async () => {
  loading.value = true
  try {
    // 使用guide.js中的getGuidePage函数
    const response = await getGuidePage(
      currentPage.value, 
      pageSize.value,
      searchForm.name || ''
    )

      guideList.value = response.records || []
      total.value = response.total || 0
  } catch (error) {
    ElMessage.error('获取讲解员列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchGuideList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  fetchGuideList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchGuideList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchGuideList()
}

// 添加讲解员
const handleAdd = () => {
  resetGuideForm()
  dialogVisible.value = true
}

// 编辑讲解员
const handleEdit = async (row) => {
  resetGuideForm()
  
  try {
    // 使用guide.js中的getGuideById函数获取详细信息
    const response = await getGuideById(row.id)

      Object.keys(guideForm).forEach(key => {
        if (key in response) {
          guideForm[key] = response[key]
        }
      })
      dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取讲解员详情失败')
  }
}

// 重置表单
const resetGuideForm = () => {
  if (guideFormRef.value) {
    guideFormRef.value.resetFields()
  }
  guideForm.id = null
  guideForm.name = ''
  guideForm.phone = ''
  guideForm.introduction = ''
  guideForm.status = 1
}

// 提交表单
const submitForm = async () => {
  if (!guideFormRef.value) return
  
  await guideFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response
        
        if (guideForm.id) {
          // 编辑 - 使用guide.js中的updateGuide函数
          response = await updateGuide(guideForm)
        } else {
          // 添加 - 使用guide.js中的addGuide函数
          response = await addGuide(guideForm)
        }

        // 根据返回值判断操作是否成功
          ElMessage.success(guideForm.id ? '更新讲解员成功' : '添加讲解员成功')
          dialogVisible.value = false
          fetchGuideList()
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

// 更改状态
const handleChangeStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    
    // 使用guide.js中的updateGuide函数
    await updateGuide({
      id: row.id,
      status: newStatus
    })
    
    // 根据返回值判断操作是否成功
      ElMessage.success(`讲解员已${newStatus === 1 ? '启用' : '禁用'}`)
      fetchGuideList()
  } catch (error) {
    ElMessage.error('更改状态失败')
  }
}

// 删除讲解员
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该讲解员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 使用guide.js中的deleteGuide函数
       await deleteGuide(row.id)
        ElMessage.success('删除讲解员成功')
        fetchGuideList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}
</script>

<style scoped>
.guide-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 22px;
  font-weight: 600;
  margin: 0;
  color: #2c3e50;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style> 